vue3的getCurrentInstance获取组件实例踩坑记录 | 您所在的位置:网站首页 › vue3 refs 子组件方法 拿不到props值 › vue3的getCurrentInstance获取组件实例踩坑记录 |
一、getCurrentInstance基本用法
我们可以通过 getCurrentInstance这个函数来返回当前组件的实例对象,也就是当前vue这个实例对象 Vue2中,可以通过this来获取当前组件实例; Vue3中,在setup中无法通过this获取组件实例,console.log(this)打印出来的值是undefined。 在Vue3中,getCurrentInstance()可以用来获取当前组件实例 常见的用途包括: 访问组件实例的属性:可以通过 getCurrentInstance().ctx 或 getCurrentInstance().proxy 来获取当前组件实例的属性。例如,可以使用 getCurrentInstance().ctx.$props 访问组件的 props 属性。 调用组件实例的方法:可以通过 getCurrentInstance().ctx 或 getCurrentInstance().proxy 来调用当前组件实例的方法。例如,可以使用 getCurrentInstance().ctx.$emit 来触发组件的自定义事件。 在生命周期钩子中使用:可以在组件的生命周期钩子中使用 getCurrentInstance() 来获取当前组件实例,以便在钩子函数中访问组件实例的属性或调用组件实例的方法。 请注意,getCurrentInstance 的返回值是一个组件实例对象,可以通过 .ctx 来访问该实例的上下文对象,或者通过 .proxy 来访问该实例的代理对象。两者的区别在于,通过 .ctx 访问的是真实的组件实例,而通过 .proxy 访问的是一个代理对象,该代理对象可以在模板中直接使用。 基本使用: import { getCurrentInstance, onMounted} from 'vue' export default { setup() { onMounted(() => { const instance = getCurrentInstance() console.log('实例', instance) }) return {} }打印出来的内容如下 代码如下: import { getCurrentInstance, onMounted} from 'vue' export default { setup() { const refName = 'cxContainer' onMounted(() => { const instance = getCurrentInstance().ctx const dom = instance.$refs[refName] console.log('dom', dom) }) return { refName } }打印结果如下: 注意:这种获取dom方式不推荐使用,具体见下文 二、getCurrentInstance使用注意点 1. getCurrentInstance 只能在 setup 或生命周期钩子中使用举个例子: import { getCurrentInstance, onMounted} from 'vue' export default { setup() { const refName = 'cxContainer' const onResize = () => { const instance = getCurrentInstance() console.log('instance', instance) } onMounted(() => { window.addEventListener('resize', onResize) }) return { refName } }以上代码我们将const instance = getCurrentInstance()放在了onResize函数中,然后在onMounted中监听浏览器尺寸变化,尺寸变化就出发onResize函数。 打印结果如下: 如需在 setup或生命周期钩子外使用,先在 setup 中调用 getCurrentInstance() 获取该实例然后再使用。 2. getCurrentInstance线上环境报错问题本地代码 import {getCurrentInstance} from "vue"; export default { setup() { const {ctx} = getCurrentInstance(); console.log('ctx', ctx) }以上代码在本地开发调试没有问题,在线上环境会报错,如果通过这个ctx.$refs[xxx]获取dom,线上就会有问题。 解决方案 使用proxy代替ctx,proxy线上不会出现问题 const { proxy } = getCurrentInstance() 三、在vue3中不推荐使用getCurrentInstance获取组件实例大家可以看看这位大佬的记录vue3中getCurrentInstance不推荐使用以及在<script setup>中获取全局内容(三种方式) 官方解释: 主要还是 getCurrentInstance 是一个内部的API,并不是公开的API,使用内部API去实现一些业务功能,可能会因为后续 Vue 的版本迭代而造成业务上的 BUG。并且 Vue3 的 Composition API 强调的就是业务的解耦和复用性,依赖组件实例属性并不是一个很好的开发方式。而 vue 相关生态的使用其实就是他们内部的事情了,他们有完善的测试用例可以跑测试,但是我们并没有,如果后续的某一个版本Vue变更了这个API,那么如果没有经过完整测试就部署上去的项目就会出现大规模的BUG反馈了 打印结果如下: |
CopyRight 2018-2019 实验室设备网 版权所有 |